//
//  CarPictureVC.m
//  New_Runway
//
//  Created by mack on 2018/1/31.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CarPictureVC.h"
#import "AddPictureCell.h"
#import "IamgeFactory.h"
#import "NRWCarPhotoManager.h"
@interface CarPictureVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (nonatomic, strong) UICollectionView *collectionview;
@property (nonatomic, assign)  NSInteger selectIndex;
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, strong) UIImage *picture;
@end

@implementation CarPictureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.hidden = YES;
    self.view.backgroundColor = kColorWhite();
    [self creatCollectionView];
    self.selectIndex = 11;
    self.isFirst = YES;
}

-(void)creatCollectionView{
    //创建一个layout布局类
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个item的大小为100*100
//    layout.itemSize = CGSizeMake(100, 80);
    layout.minimumLineSpacing      = 5;
    layout.minimumInteritemSpacing = 5;
    //    [layout setHeaderReferenceSize:CGSizeMake(Screen_width, self.view.frame.size.width * 3 / 5)];
    //创建collectionView 通过一个布局策略layout来创建
    _collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, Screen_width, Screen_height  - self.BotH - self.navH - 40) collectionViewLayout:layout];
    //代理设置
    _collectionview.backgroundColor = UIColorHex(0xf5f5f5);
    _collectionview.delegate=self;
    _collectionview.dataSource=self;
    //注册item类型 这里使用系统的类型
    [_collectionview registerNib:[UINib nibWithNibName:@"AddPictureCell" bundle:nil] forCellWithReuseIdentifier:@"AddPictureCell"];

    [self.view addSubview:_collectionview];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 10;

}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *array = @[@"左前（首图）",@"VIN",@"右后",@"驾驶座椅",@"控制室",@"里程表",@"打开后备箱",@"发动机全景",@"变速档杆",@"轮胎"];
  
    AddPictureCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddPictureCell" forIndexPath:indexPath];
    [cell configData:nil indexPath:indexPath];
    cell.delateBtn.hidden = NO;
  
    if (_isFirst == YES) {
        
   
    if (indexPath.row == 0) {
            [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.left_anterior]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        cell.delateBtn.hidden = YES;

        
    }else if (indexPath.row == 1){

            [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.vin]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.vin isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }

    }else if (indexPath.row == 2){
        
              [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.right_rear]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.right_rear isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
      

    }else if (indexPath.row == 3){
        
              [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.driving_seat]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.driving_seat isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
      
        
    }else if (indexPath.row == 4){
        
              [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.control_booth]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.control_booth isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
      
        
    }else if (indexPath.row == 5){
        [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.odograph]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.odograph isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
        
    }else if (indexPath.row == 6){
        [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.open_trunk]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.open_trunk isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
        
    }else if (indexPath.row == 7){
        [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.engine_bay]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.engine_bay isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
    }else if (indexPath.row == 8){
        [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.gear_lever]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.gear_lever isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
    }else if (indexPath.row == 9){
       
        [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ImageApi,self.imageModel.tyre]] placeholderImage:[UIImage imageNamed:@"addPic"]];
        if ([self.imageModel.tyre isEqualToString:@""]) {
            cell.delateBtn.hidden = YES;
        }
    }
    }else{
        
        if (self.selectIndex == indexPath.row) {
            cell.mainImage.image = self.picture;
            if (indexPath.row == 0) {
                cell.delateBtn.hidden = YES;
            }

        }
        
    }

    cell.mainTitle.text = array[indexPath.row];
    

    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake((Screen_width - 50) / 3, (Screen_width - 40) / 3 - 40);
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section

{
    return UIEdgeInsetsMake(10, 15, 0, 15);//分别为上、左、下、右
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
    self.selectIndex = indexPath.row;
    
    [self editPeopleMessage];
    
    
}
-(void)editPeopleMessage{
    
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"拍照时建议横屏拍摄" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"拍照时建议横屏拍摄" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
    }
    
    
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {

            case 0: //相机
                [self choosePictureType:YES];
               
                break;
            case 1: //相册
                
                [self choosePictureType:NO];

                break;
            case 2:
                return;
                break;
        }
    }
    else {
        switch (buttonIndex) {
            case 0:
                [self choosePictureType:NO];

                break;
            case 1:
                return;
                break;

        }
    }
//    // 跳转到相机或相册页面
//    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//    imagePickerController.delegate = self;
//    imagePickerController.allowsEditing = YES;
//    imagePickerController.sourceType = sourceType;
//
//    [self presentViewController:imagePickerController animated:YES completion:^{}];

    
}

-(void)choosePictureType:(BOOL)isCamre{
    kSelfWeak;
    if (isCamre == YES) {
        [[NRWCarPhotoManager shareInstance] presentPicker:PickerType_Camera photoCut:PhotoCutType_YES target:self callBackBlock:^(UIImage *image, BOOL isCancel) {
            if (image) {
                NSData *data = [UIImage compressImage:image maxSize:1000 maxFileSize:300];
                weakSelf.isFirst = NO;
                weakSelf.picture = image;
                [weakSelf.collectionview reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectIndex inSection:0]]];
                [weakSelf uploadCarImage:weakSelf.selectIndex Image:data];
            }
            
        }];
    }else{
        [[NRWCarPhotoManager shareInstance] presentPicker:PickerType_Photo photoCut:PhotoCutType_YES target:self callBackBlock:^(UIImage *image, BOOL isCancel) {
            if (image) {
                NSData *data = [UIImage compressImage:image maxSize:1000 maxFileSize:300];
                weakSelf.isFirst = NO;
                weakSelf.picture = image;
                [weakSelf.collectionview reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectIndex inSection:0]]];
                [weakSelf uploadCarImage:weakSelf.selectIndex Image:data];
            }
           
        }];
    }
    
}
//
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
//{
//    [picker dismissViewControllerAnimated:YES completion:^{}];
//    
//    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//    
//    NSData *data = [UIImage compressImage:image maxFileSize:300];
//    _isFirst = NO;
//    self.picture = image;
//    [self.collectionview reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectIndex inSection:0]]];
//
//    [self uploadCarImage:self.selectIndex Image:data];
//
//    
//}

-(void)uploadCarImage:(NSInteger)selected Image:(NSData *)image{
    NSDictionary *params;
    NSArray *keyArray = @[@"left_anterior",@"vin",@"right_rear",@"driving_seat",@"control_booth",@"odograph",@"open_trunk",@"engine_bay",@"gear_lever",@"tyre"];
        params = @{
                   @"carId":self.carID,
                   @"imageKey":keyArray[selected],
                   };
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,uploadImageApi];
    [SVProgressHUD show];
    [YQNetworking uploadFileWithUrl:url params:params fileData:image type:@"jpg" name:@"uploadFile" mimeType:@"image/*" progressBlock:^(int64_t bytesWritten, int64_t totalBytes) {

    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            [self.imageModel setValue:response[@"result"][@"pathUrl"] forKey:keyArray[selected]];
            [ShowMessage showHintMessage:@"上传成功" duration:2.0 withRemindId:remindSuccess];

        }else{
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindFail];

        }
        [SVProgressHUD dismiss];
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"上传失败，请检查网络是否流畅" duration:2.0 withRemindId:remindFail];

    }];

    
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    NSIndexPath *index = userInfo[@"index"];
    NSArray *keyArray = @[@"left_anterior",@"vin",@"right_rear",@"driving_seat",@"control_booth",@"odograph",@"open_trunk",@"engine_bay",@"gear_lever",@"tyre"];

    if ([eventName isEqualToString:@"delate"]) {
        _isFirst = YES;
        [self.imageModel setValue:@"" forKey:keyArray[index.row]];
        [self.collectionview reloadData];
    }
    
}
-(void)saveIamgeToFactory{
 
    IamgeFactory *iamgeUser = [IamgeFactory sharedMemory];
    [iamgeUser setValuesForKeysWithDictionary:[self.imageModel mj_keyValues]];
    [iamgeUser save];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigationcon
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
